define(['WebPDF',
		'./models/PDFDocument',
		'./models/PDFPage',
		'./models/PDFDocProperties'], 
	function (WebPDF, PDFDocument, PDFPage, PDFDocProperties) {
		'use strict';
	WebPDF.factory('PDFDocService', ['$http', '$q', '$log', 'PDFConfig',
		function($http, $q, $log, PDFConfig) {
			var _pdfDoc = null;			

			function _makeUrl () {
				var url = PDFConfig.baseUrl + PDFConfig.s3Key + "/PagesInfo_form";
				return url;
			}

			function _createPDFDoc(docInfo) {
				try {
					_pdfDoc = new PDFDocument(docInfo.doctype);
					_pdfDoc.pageCount = docInfo.PageCount;

					var i = 0;
					angular.forEach(docInfo.PagesInfo, function(pageInfo) {
						var pdfPage = new PDFPage(pageInfo);
						pdfPage.pageIndex = i++;
						_pdfDoc.addPage(pdfPage);
					});

					if (docInfo.dppinfo && docInfo.dppinfo.ppt) {
						var pDocProperties = new PDFDocProperties(docInfo.dppinfo.ppt);
						_pdfDoc.setDocProperties(pDocProperties);
					} else
						_pdfDoc.setDocProperties(null);
				} catch (ex) {
					$log.error(ex);
					return null;
				}
			}


			function _makePageImgUrl(page){
				var url =  PDFConfig.baseUrl + PDFConfig.s3Key + "/page_" + page.pageIndex + '_zoom_100_1?ate=1';
				return url;
			}

			function _loadDocument () {
				var deferred = $q.defer();
				$http.get(_makeUrl())
					.success(function(data) {
						_createPDFDoc(data);
						deferred.resolve(_pdfDoc);
					})
					.error(function(data) {
						deferred.reject('there was an error');		
					});
				return deferred.promise;
				
			}

			function _loadPage (page) {				
				var imgUrl = _makePageImgUrl(page);
				var req = {
					method: 'GET',
					url: 'imgUrl',
					headers: {
						'Accept': 'image/png',
						'Content-Type': 'image/png'
					}
				};

				return new Promise(function(resolve, reject) {
					$http.get(imgUrl, {cache: true})
					.success(function(data) {					
						page.imageUrl = imgUrl;
						page.isLoaded = true;
						resolve(page);
					})
					.error(function(data) {
						reject('there was an error');
					});
				});
			}

			return {
				getManifest: function() {},
				getPDFDoc: function() {					
					//如果文档未加载，就执行加载过程
					
					if (!_pdfDoc) {
						return _loadDocument();							
					} else {
						return $q.resolve(_pdfDoc);
					}					
				},

				loadPDFPage: function(page){					
					if (!page.isLoaded){
						return _loadPage(page);						
					}else {
						return Promise.resolve(page);
					}					
				},
			};
		}
	]);
});